import 'package:aitao_flutter/common_ui/circle_avatar.dart';
import 'package:aitao_flutter/style/box_style.dart';
import 'package:aitao_flutter/style/color_style.dart';
import 'package:aitao_flutter/style/edgeInsets_style.dart';
import 'package:aitao_flutter/style/radius_style.dart';
import 'package:aitao_flutter/style/text_style.dart';
import 'package:aitao_flutter/utils/log_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:nim_chatkit_ui/chat_page.dart';
import 'package:nim_core/nim_core.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../common_ui/empty_view.dart';
import '../model/intimate_friend_mode.dart';
import '../refresh/custom_refresh_footer.dart';
import '../refresh/custom_refresh_header.dart';
import '../request/api.dart';
import '../request/requestManager.dart';

class IntimacyListPage extends StatefulWidget {
  const IntimacyListPage({Key? key}) : super(key: key);

  @override
  State<IntimacyListPage> createState() => _IntimacyListPageState();
}

class _IntimacyListPageState extends State<IntimacyListPage> with AutomaticKeepAliveClientMixin {

  @override
  bool get wantKeepAlive => true;

  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  final List<IntimateModel> _list = [];
  int _page = 1;
  int _totalPage = 1;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return _list.isEmpty
        ? EmptyView()
        : SmartRefresher(
            controller: _refreshController,
            enablePullDown: true,
            enablePullUp: _page < _totalPage,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            header: CustomClassicHeader(),
            footer: const CustomClassicFooter(),
            child: ListView.builder(
              itemBuilder: ((context, index) {
                return _intimacyItem(index);
              }),
              itemCount: _list.length,
            ),
          );
  }

  Widget _intimacyItem(int index) {
    IntimateModel model = _list[index];
    return GestureDetector(child: Container(
      color: ColorStyle.whiteColor,
      padding: EdgeInsetsStyle.edgeInsets(16, 10),
      child: Row(
        children: [
          CircleAvatarWidget(
              url: model.avatar ?? '', gender: model.gender ?? 1),
          Box.hBox10,
          Text(
            model.nickname ?? '',
            style: Styles.normalText_15,
          ),
          Box.hBox5,
          Container(
            decoration: BoxDecoration(
                borderRadius: RadiusStyle.radiusAll(2.5),
                color: ColorStyle.setColor(0xFF50de30)),
            width: 5.w,
            height: 5.w,
          ),
          Box.hBox5,
          Text(
            model.dateline ?? '',
            style: Styles.greyText_14,
          ),
          const Spacer(),
          Text('默契值${model.intimateDegree.toString()}' ,style:TextStyle(fontSize: 11,color: ColorStyle.setColor(0xFFF65454)),)
        ],
      ),
    ),onTap: (){
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return ChatPage(
            sessionId: model.userId.toString(),
            sessionType: NIMSessionType.p2p);
      }));
    },);
  }

  @override
  void initState() {
    super.initState();
    loadNewList();
  }

  void loadNewList() async {
    var result =
        await RequestManager().post(API.getFriendshipList, params: {'page': _page});
    if (result != null && result['code'] == 0) {
      _list.clear();
      _page = result['data']['page'];
      _totalPage = result['data']['total_page'];
      List tempList = result['data']['list'];
      for (var element in tempList) {
        IntimateModel m = IntimateModel.fromJson(element);
        _list.add(m);
      }
      if (_page >= _totalPage) {
        _refreshController.loadNoData();
      }
      if (mounted) {
        setState(() {});
      }
    }
  }

  void loadMoreList() async {
    var result = await RequestManager()
        .post(API.fansList, params: {'type': 0, 'page': _page});
    if (result != null && result['code'] == 0) {
      _page = result['data']['page'];
      _totalPage = result['data']['total_page'];
      if (_page >= _totalPage) {
        _refreshController.loadNoData();
      }
      List tempList = result['data']['list'];
      _list.addAll(tempList.map((e) {
        IntimateModel m = IntimateModel.fromJson(e);
        return m;
      }));
      if (mounted) {
        setState(() {});
      }
    }
  }

  void _onRefresh() {
    _page = 1;
    _totalPage = 1;
    loadNewList();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    _page += 1;
    loadMoreList();
    _refreshController.loadComplete();
  }

  /// 获取好友个数
  void getFriendList() async {
    debugPrint('获取好友个数');
    var result =
        await RequestManager().post(API.getFriendshipList, params: {'page': 1});
    if (result != null && result['code'] == 0) {
      // Map data = result['data'];
      // friendCount = data['total'];
      // update();
      WJLogUtils.wjLog(result);
    }
  }
}
